package com.huluobo.sign.pages

import android.text.TextUtils
import android.util.Log
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.navigation.NavHostController
import com.amap.api.maps.AMap
import com.amap.api.maps.MapView
import com.amap.api.maps.model.MyLocationStyle
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.huluobo.lib_base.BaseApp
import com.huluobo.lib_base.BaseTitle
import com.huluobo.lib_http.Const
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.sql.Time
import java.text.SimpleDateFormat
import java.util.Timer
import kotlin.concurrent.timerTask

/**
 *  Created by LC on 2025/7/14.
 */
lateinit var mapView: MapView
lateinit var map: AMap
lateinit var myLocationStyle: MyLocationStyle
lateinit var geocodeSearch: GeocodeSearch
lateinit var query: RegeocodeQuery

lateinit var timer: Timer

@Composable
fun SignCommitPage(navHostController: NavHostController) {

    var startTime by remember {
        mutableStateOf("上班还未打卡")
    }

    var endTime by remember {
        mutableStateOf("下班还未打卡")
    }

    var btnName by remember {
        mutableStateOf("上班打卡")
    }

    var nowTime by remember {
        mutableStateOf("00:00:00")
    }

    var enable by remember {
        mutableStateOf(true)
    }

    val kv = MMKV.defaultMMKV()

    LaunchedEffect(key1 = "", block = {
        launch {
            timer = Timer()
            timer.schedule(timerTask {
                nowTime = SimpleDateFormat("HH:mm:ss").format(System.currentTimeMillis())
            }, 0, 1000)
        }

        launch {
            val signTime = kv.decodeString(Const.PARAM_SIGN_IN, "").toString()
            if (!TextUtils.isEmpty(signTime)) {
                val time = SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis())
                val statusIn = kv.decodeString(Const.PARAM_STATUS_IN).toString()
                val signDate = signTime.substring(0, 10)
                if (time == signDate) {
                    startTime = "上班时间 : $signTime $statusIn"
                    btnName = "下班打卡"
                    val outTime = kv.decodeString(Const.PARAM_SIGN_OUT, "").toString()
                    if (!TextUtils.isEmpty(outTime)) {
                        val statusOut = kv.decodeString(Const.PARAM_STATUS_OUT).toString()
                        val outDate = outTime.substring(0, 10)
                        if (time == outDate) {
                            endTime = "下班时间 : $outTime $statusOut"
                            enable = false
                        }
                    }
                } else {
                    btnName = "上班打卡"
                }
            }
        }
    })

    Column(
        Modifier.padding(10.dp),
        verticalArrangement = Arrangement.spacedBy(10.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        BaseTitle(title = "签到/签退", navHostController = navHostController)

        AndroidView(modifier = Modifier.height(300.dp), factory = {
            mapView = MapView(it)
            mapView.onCreate(null)
            map = mapView.map
            myLocationStyle = MyLocationStyle()
            myLocationStyle.interval(2000)
            map.myLocationStyle = myLocationStyle
            map.isMyLocationEnabled = true

            map.addOnMyLocationChangeListener { location ->
                geocodeSearch = GeocodeSearch(BaseApp.context)
                query = RegeocodeQuery(LatLonPoint(location.latitude, location.longitude), 2000f, GeocodeSearch.AMAP)
                geocodeSearch.getFromLocationAsyn(query)
                geocodeSearch.setOnGeocodeSearchListener(object : GeocodeSearch.OnGeocodeSearchListener {
                    override fun onRegeocodeSearched(result: RegeocodeResult?, error: Int) {
                        Log.e("TagA", "定位地址:${result?.regeocodeAddress?.formatAddress}")
                    }

                    override fun onGeocodeSearched(p0: GeocodeResult?, p1: Int) {
                    }

                })
            }

            mapView
        })

        Spacer(modifier = Modifier.height(50.dp))
        Text(
            text = startTime, modifier = Modifier
                .fillMaxWidth()
                .padding(start = 20.dp)
        )
        Spacer(modifier = Modifier.height(10.dp))
        Text(
            text = endTime, modifier = Modifier
                .fillMaxWidth()
                .padding(start = 20.dp)
        )
        Spacer(modifier = Modifier.height(20.dp))
        Button(
            onClick = {
                //点击签到或者签退
                val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())
                val workStart = "08:30:00"
                val workEnd = "17:00:00"
                if (btnName == "上班打卡") {
                    kv.encode(Const.PARAM_SIGN_IN, time)
                    val status = if (time.substring(11, time.length) > workStart) "迟到" else "正常"
                    kv.encode(Const.PARAM_STATUS_IN, status)
                    startTime = "上班时间 : $time $status"
                    btnName = "下班打卡"
                } else {
                    kv.encode(Const.PARAM_SIGN_OUT, time)
                    val status = if (time.substring(11, time.length) < workEnd) "早退" else "正常"
                    kv.encode(Const.PARAM_STATUS_OUT, status)
                    endTime = "下班时间 : $time $status"
                    enable = false
                }
            }, modifier = Modifier
                .size(140.dp)
                .clip(CircleShape), enabled = enable
        ) {
            Column {
                Text(text = btnName, fontSize = 22.sp)
                Text(text = nowTime, fontSize = 22.sp)
            }
        }

        Spacer(modifier = Modifier.height(10.dp))
        Button(onClick = {
            kv.remove(Const.PARAM_SIGN_IN)
            kv.remove(Const.PARAM_SIGN_OUT)
        }) {
            Text(text = "清空kv")
        }
    }
}